package com.devfest.wishmaster.model;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.devfest.wishmaster.gui.MyApplication;

public class JSONParser {

	private static final String TAG_ID = "ID";
	private static final String TAG_NAME = "Name";
	private static final String TAG_DATE_CREATED = "DateCreated";
	private static final String TAG_EVENT_DATE = "EventDate";
	private static final String TAG_USER = "User";
	private static final String TAG_WISH_LISTS = "WishLists";
	private static final String TAG_W_LIST = "WList";
	private static final String TAG_ITEMS = "Items";
	private static final String TAG_DESCRIPTION = "Description";
	private static final String TAG_PRICE = "Price";
	private static final String TAG_MODE = "Mode";
	private static final String TAG_IMAGE_PATH = "ImagePath";
	private static final String TAG_TITLE = "Title";

	private static JSONParser instance;
	
	public static JSONParser getInstance() {
		if (instance == null) {
			instance = new JSONParser();
		}
		return instance;
	}

	private JSONObject getJSONFromUrl(String url, List<NameValuePair> params)
			throws Exception {
		
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 10000); // Timeout
		try {
			// for (NameValuePair nameValuePair : params)
			// if (nameValuePair.getValue().contains(",")) {
			// JSONArray jArray2 = new JSONArray();
			// Object[] objects = nameValuePair.getValue().split(",");
			// for (int i = 1; i < objects.length; i++)
			// jArray2.put(Integer.parseInt(objects[i].toString()));
			// jObj.put(nameValuePair.getName(), jArray2);
			// } else
			// jObj.put(nameValuePair.getName(), nameValuePair.getValue());
			// StringEntity se = new StringEntity(jObj.toString());
			// se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
			// "application/json"));
			//
			// HttpPost httpPost = new HttpPost(url);
			// httpPost.setEntity(se);

			HttpGet request = new HttpGet();
			request.setURI(new URI(url));
			InputStream is = null;
			HttpResponse httpResponse = httpClient.execute(request);

			if (httpResponse != null) {
				is = httpResponse.getEntity().getContent();
			}

			BufferedReader rd = new BufferedReader(new InputStreamReader(is,
					Charset.forName("UTF-8")));
			StringBuilder sb = new StringBuilder();
			int cp;
			while ((cp = rd.read()) != -1) {
				sb.append((char) cp);
			}
			is.close();
			String json = sb.toString();
			return new JSONObject(json);
		} catch (Exception e) {
			Log.e("DevFest", "error in getJSONFromUrl()", e);
			throw e;
		}
	}

	public void checkComments() throws Exception {
		String url = "http://www.gdgtbilisi.upwebsite.info/user-service.php?user=maka@gmail.com&pass=maka&checkcomment=1&format=json";
		JSONObject jObject = getJSONFromUrl(url, null);
		for (int i = 0; i < MyApplication.getInstance().wishLists.size(); i++) {
			for (int j = 0; j < MyApplication.getInstance().wishLists.get(i).getWishItems().size(); j++) {
				for (int k = 0; k < MyApplication.getInstance().wishLists.get(i).getWishItems().get(j).getNewComments().size(); k++) {
					MyApplication.getInstance().wishLists
							.get(i)
							.getWishItems()
							.get(j)
							.getComments()
							.add(MyApplication.getInstance().wishLists.get(i)
									.getWishItems().get(j).getNewComments()
									.get(k));
				}
				MyApplication.getInstance().wishLists.get(i).getWishItems().get(j).getComments().clear();
			}
		}
	}

	public List<WishList> getWishList(List<NameValuePair> params)
			throws Exception {
		List<WishList> wishLists = new ArrayList<WishList>();
		String url = "http://www.gdgtbilisi.upwebsite.info/user-service.php";
		url += "?" + params.get(0).getName() + "=" + params.get(0).getValue()
				+ "&" + params.get(1).getName() + "="
				+ params.get(1).getValue() + "&format=json";
		JSONObject jObject = getJSONFromUrl(url, params);
		MyApplication.getInstance().userFullName = jObject
				.getString("FullName");
		if (MyApplication.getInstance().userFullName.equals("null")) {
			MyApplication.getInstance().userFullName = "";
			throw new Exception();
		}
		JSONArray jArray = jObject.getJSONArray(TAG_WISH_LISTS);
		for (int i = 0; i < jArray.length(); i++) {
			jObject = jArray.getJSONObject(i).getJSONObject(TAG_W_LIST);
			WishList wishList = new WishList();
			wishList.setId(jObject.getInt(TAG_ID));
			wishList.setName(jObject.getString(TAG_NAME));
			wishList.setDateCreated(jObject.getString(TAG_DATE_CREATED));
			wishList.setEventDate(jObject.getString(TAG_EVENT_DATE));
			wishList.setUser(jObject.getInt(TAG_USER));
			if (jObject.has(TAG_ITEMS)) {
				JSONArray itemArray = jObject.getJSONArray(TAG_ITEMS);
				for (int j = 0; j < itemArray.length(); j++) {
					JSONObject itemObject = itemArray.getJSONObject(j);
					WishItem item = new WishItem();
					item.setId(itemObject.getInt(TAG_ID));
					item.setDateCreated(itemObject.getString(TAG_DATE_CREATED));
					item.setPrice(itemObject.getDouble(TAG_PRICE));
					item.setDescription(itemObject.getString(TAG_DESCRIPTION));
					item.setTitle(itemObject.getString(TAG_TITLE));
					item.setMode(itemObject.getInt(TAG_MODE));
					item.setImage(itemObject.getString(TAG_IMAGE_PATH));
					if (itemObject.has("Comments")) {
						item.getNewComments().clear();
						JSONArray commentsArray = itemObject.getJSONArray("Comments");
						for (int k = 0; k < commentsArray.length(); k++) {
							JSONObject jobj = commentsArray.getJSONObject(k);
							Comment comment = new Comment();
							comment.setId(jobj.getInt(TAG_ID));
							comment.setDatecreated(jobj
									.getString(TAG_DATE_CREATED));
							comment.setUser(jobj.getString(TAG_USER));
							comment.setText(jobj.getString("Text"));
							comment.setWishItem(item);
							item.getNewComments().add(comment);
						}
					}
					item.setWishList(wishList);
					wishList.getWishItems().add(item);
				}
			}
			wishLists.add(wishList);
		}
		return wishLists;
	}
}